var j$ = jQuery;

var Page ={
    closeWindow: false,
    tripId: $('#content').attr('data-trip-pk'),
    CSRF: $('#csrf_token').attr('data-csrf'),
    snsType: $("#content").attr("data-sns-type"),
    loadPage: 2,
    uploadUrl: $('#content').attr('data-upload'),
    statusUrl: $('#content').attr('data-status'),
    nextBtn: $('#btn-next'),
    nextUrl: $('#content').attr('data-next-url'),
    updateTripStatus: function () {
        var _name = $('#trip-name').text();
        var _privacy = $('#trip-privacy').val();
        if ( _name === '' ) {
            alert('游记还没有名字');
            // $('#trip-name').focus();
            // $('#trip-name-error').text('起个响亮的名字吧');
            return false;
        }
        $.ajax({
            url: Page.statusUrl,
            type: 'POST',
            dataType: 'json',
            data: {
                'csrfmiddlewaretoken': Page.CSRF,
                'trip_name': _name,
                'privacy': _privacy
            },
            success: function (data) {
                if ( data.success ) {
                    Page.uploadPhotos();
                }else{
                    alert(data);
                }
            }
        });
    },
    verifyTripName: function () {
        if ( $('#trip-name-input').val() === '' ) {
            $('#trip-name').addClass('error').text('起个响亮的名字吧');
        }else{
            Page.updateTripStatus();
        }
    },
    uploadPhotos: function () {
        // var _loading = $('#uploader-sns-msg');
        if( Page.nextBtn.hasClass('disabled') ) {
            return false;
        }
        Page.nextBtn.addClass('disabled');
        // _loading.show();
        var data = {csrfmiddlewaretoken: Page.CSRF};
        var ids = [];
        $('#filelist').find('.selected').each(function() {
            var _id = $(this).attr('data-pk');
            if(_id) {
                ids.push(_id);
            }
        });
        data['pub_ids'] = ids;
        var _url = '/trips/' + Page.tripId + '/upload_photos/set_privacy/?mode=create';
        $.ajax({
            url: _url,
            type: 'POST',
            data: data,
            success: function(resp) {
                if(!resp.error) {
                    $(window.location).attr('href', resp.new_edit_link);
                } else {
                    // console.log(resp.error);
                    Page.nextBtn.removeClass('disabled');
                    // _loading.hide();
                }
            }
        });
        return false;
    },
    refreshDoneButton: function() {
        Page.nextBtn.addClass('disabled');
        var photo_upload = false;
        var photos = $('#filelist li[data-finished]');
        for (var i = 0; i < photos.length; i++) {
            if ($(photos[i]).attr('data-finished') == '0') {
                photo_upload = true;
                break;
            }
        }
        if( !photo_upload && $('#filelist .selected').length > 0 ) {
            Page.nextBtn.removeClass('disabled');
            // $('#uploader-sns-msg').hide();
            Page.closeWindow = true;
        } else {
            Page.nextBtn.addClass('disabled');
            // $('#uploader-sns-msg').show();
            Page.closeWindow = false;
        }
    },
    initPhotoEvents: function () {
        function _selectPhoto ( photo, pk ) {
            photo.attr({
                'data-finished': 1,
                'data-pk': pk
            });
            Page.refreshDoneButton();
        }
        function _savePhoto (e) {
            e.preventDefault();
            var _this = $(this);
            if ( _this.hasClass('selected') ) {
                _this.removeClass('selected');
                Page.refreshDoneButton();
            } else{
                if ( _this.attr('data-pk') === undefined ) {
                    var _id = _this.attr('data-id');
                    var _text = _this.attr('title');
                    var _lat = _this.attr('data-lat');
                    var _lng = _this.attr('data-lng');
                    var _picurl = _this.attr('data-pic-url');
                    var _privacy = _this.attr('data-privacy');
                    var _createdat = _this.attr('data-created-time');
                    $.ajax({
                        url: Page.uploadUrl,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            csrfmiddlewaretoken: Page.CSRF,
                            id: _id,
                            text: _text,
                            lat: _lat,
                            lng: _lng,
                            pic_url: _picurl,
                            privacy: _privacy,
                            created_time: _createdat
                        },
                        beforeSend: function(){
                            _this.addClass('selected');
                            Page.nextBtn.addClass('disabled');
                        }
                    }).done(function(data) {
                        if ( data.success ) {
                            _selectPhoto( _this, data.pk );
                        }else{
                            _this.removeAttr('data-pk').removeAttr('data-finished').addClass('fail').removeClass('selected').find('.select-text').text('重新上传');

                            // $(a).removeAttr('data-pk').removeAttr('data-finished').addClass('fail').removeClass('selected').find('span').text('重新上传');
                        }
                    }).fail();
                }else{
                    _this.addClass('selected').find('.select-text').text('选择照片');
                    Page.refreshDoneButton();
                }
            }
        }
        $('#filelist').on('click', 'li', _savePhoto);
        $("#load-more").on("click", Page.loadMorePhotos);
    },
    loadMorePhotos: function () {
        $('#ajax-more').show();
        var _content = '';
        $.ajax({
            url: '/sns/photos/',
            type: 'GET',
            dataType: 'json',
            data: {
                csrfmiddlewaretoken: Page.CSRF,
                sns_type: Page.snsType,
                page: Page.loadPage,
                next_page_url: Page.nextUrl
            },
            success: function(resp) {
                if ( resp.success ) {
                    $.each(resp.photos, function(index, val) {
                        _content += '<li title="' + val.text
                                  + '" data-created-time="'+val.created_time
                                 +'" data-pic-url="'+val.pic_url
                                 +'"';
                        if ( val.lat ){
                            _content +=' data-lat="{{i.lat}}" data-lng="{{i.lng}}"';
                        }
                        _content += ' data-id="'+val.id
                                 + '" data-privacy="'+val.privacy +'" class="photo-tile sns-tile"><p class="photo" style="background-image: url(' + val.thumbnail
                                 + ')"></p><p class="selected-icon"><i class="edit-trip-icons-selected"></i></p><p class="select-text">选择照片</p>';
                        if ( val.lat ){
                            _content += '<i class="edit-trip-icons-loc"></i>';
                            
                        }
                        _content += '</li>';
                    });
                    Page.loadPage = resp.page + 1;
                    Page.nextUrl = resp.next_page_url;
                    $(_content).appendTo('#filelist');
                    $('#ajax-more').hide();
                }else{
                    $('#load-more').hide();
                    // console.log( resp.msg );
                }
            }
        })
        .done(function(data) {
            // console.log(data);
        })
        .fail(function() {
            // console.log('error');
        })
        .always(function() {
            // console.log('complete');
        });
    },
    alertUnsavedChange: function () {
        if ( !Page.closeWindow ) {
            return '您尚有未完成的操作，确定离开？';
        }
    },
    initChangeTripName: function () {
        $('#trip-name-form').attr('data-trip-id', Page.tripId);
        $('#trip-name').text('');
        $('#trip-name-input').val('');
    },
    initNextEvents: function () {
        $(window).on('beforeunload', function() {
            return Page.alertUnsavedChange();
        });
        Page.nextBtn.on('click', function(e) {
            e.preventDefault();
            Page.verifyTripName();
        });

        // $('#uploader-sns-form').on('submit', function(e) {
        //     e.preventDefault();
        //     Page.updateTripStatus();
        // });
    }

};

$(function(){
    Page.initChangeTripName();
    Page.initPhotoEvents();
    Page.initNextEvents();
});
